import paramiko

conf = {
    '196.168.8.120': ('root', 'cavlin'),
}


class SSHConnection(object):
    def __init__(self, host, port,user,passwd):
        self._host = host
        self._port = port
        self._username = user
        self._password = passwd
        self._transport = None
        self._sftp = None
        self._client = None
        self._connect()  # 建立连接

    def _connect(self):
        transport = paramiko.Transport((self._host, self._port))
        transport.connect(username=self._username, password=self._password)
        self._transport = transport

    # 下载
    def download(self, remotepath, localpath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.get(remotepath, localpath)

    # 上传
    def put(self, localpath, remotepath):
        if self._sftp is None:
            self._sftp = paramiko.SFTPClient.from_transport(self._transport)
        self._sftp.put(localpath, remotepath)

    def __enter__(self):
        if self._client is None:
            self._connect()
            return self

    # with self:语句体内容结束后执行如下方法 先执行__enter__方法
    def __exit__(self, exc_type, exc_val, exc_tb):
        self._client.close()
        self._client = None
    # 执行命令

    def exec_command(self, command):
        if self._client is None:
            self._client = paramiko.SSHClient()
            self._client._transport = self._transport
        stdin, stdout, stderr = self._client.exec_command(command)
        out_data = stdout.read().decode('utf-8').strip()
        returncode = stdout.channel.recv_exit_status()
        if len(out_data) > 0:
            # try:
            #     print(data.decode('utf-8').strip())
            # except UnicodeDecodeError:
            #     print(data.decode('gbk').strip())
            return out_data
        err_data = stderr.read().decode('utf-8').strip()
        if len(err_data) > 0:
            # try:
            #     print(err.decode('utf-8').strip())
            # except UnicodeDecodeError:
            #     print(err.decode('gbk').strip())
            return err_data
        # print("返回值：",returncode)
        return (returncode)

    def close(self):
        if self._transport:
            self._transport.close()
        if self._client:
            self._client.close()


# def run_ssh_command(ip,command):
#     conn = SSHConnection(ip,22)
#     if conn.exec_command(command):
#         return 1
#     else:
#         return 0

if __name__ == "__main__":
    conn = SSHConnection('196.168.41.222', 22)
    a = conn.exec_command('df -h')
    print(a)
